package com.android.library.utils;

import android.content.Context;
import android.text.Html;
import android.text.Spanned;
import android.text.TextUtils;

import java.lang.reflect.Field;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * @author xiaoxoing
 * @Description : 字符串工具类
 */
public class StringUtils {
    /**
     * 正则表达式：验证邮箱
     */
    private static final String REGEX_EMAIL = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";

    /**
     * 判断字符串不为空
     *
     * @param string
     * @return
     */
    public static boolean isNotEmpty(String string) {
        return !TextUtils.isEmpty(string);
    }

    /**
     * 判断字符串为空
     *
     * @param string
     * @return
     */
    public static boolean isEmpty(String string) {
        return TextUtils.isEmpty(string);
    }

    /**
     * 判断是否是大于等于1整数
     *
     * @param string
     * @return
     */
    public static boolean isInteger(String string) {
        String regEx = "[1-9]\\d*";
        Pattern pattern = Pattern.compile(regEx);
        Matcher matcher = pattern.matcher(string);
        return matcher.matches();
    }

    /**
     * 判断手机号码
     */
    public static boolean isMobileNo(String mobiles) {
        if (mobiles == null) {
            return false;
        }
        return mobiles.length() == 11;

    }

    /**
     * 校验邮箱
     *
     * @param email
     * @return 校验通过返回true，否则返回false
     */
    public static boolean isEmail(String email) {
        return Pattern.matches(REGEX_EMAIL, email);
    }

    /**
     * 只允许汉字
     */
    public static String stringFilter(String str) throws PatternSyntaxException {
        String regEx = "[^\u4E00-\u9FA5]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    /**
     * 不允许汉字
     */
    public static String stringFilterWord(String str) throws PatternSyntaxException {
        String regEx = "[\u4E00-\u9FA5]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    /**
     * 将字符串全角化
     */
    public static String half2full(String str) {
        char[] c = str.toCharArray();
        for (int i = 0; i < c.length; i++) {
            if (c[i] == 12288) {
                c[i] = (char) 32;
                continue;
            }
            if (c[i] > 65280 && c[i] < 65375) {
                c[i] = (char) (c[i] - 65248);
            }
        }
        return new String(c);
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 得到状态栏高度
     */
    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    public static int getStatusBarHeights(Context context) {
        Class<?> c = null;
        Object obj = null;
        Field field = null;
        int x = 0, statusBarHeight = 0;
        try {
            c = Class.forName("com.android.internal.R$dimen");
            obj = c.newInstance();
            field = c.getField("status_bar_height");
            x = Integer.parseInt(field.get(obj).toString());
            statusBarHeight = context.getResources().getDimensionPixelSize(x);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        return statusBarHeight;
    }

    /**
     * 使用String的split 方法
     */
    public static String[] convertStrToArray(String str) {
        String content = half2full(str);
        String[] strArray = null;
        //拆分字符为"," ,然后把结果交给数组strArray
        strArray = content.split(",");
        return strArray;
    }

    public static String[] convertStrToArray(String str, String flag) {
        if (StringUtils.isEmpty(str)) {
            return null;
        }
        String content = half2full(str);
        String[] strArray = null;
        //拆分字符 ,然后把结果交给数组strArray
        strArray = content.split(flag);
        return strArray;
    }

    /**
     * 字符串最后是否“万”字结尾,如果是则截去
     */
    public static String numChage(String str) {
        String num = str;
        if (str.endsWith("万")) {
            num = str.substring(0, str.lastIndexOf('万'));
        }
        return num;
    }

    /**
     * 截取字符串
     *
     * @param targetStr
     * @param strlength 截取的长度
     * @return
     */
    public static String getSubstring(String targetStr, int strlength) {

        if (StringUtils.isEmpty(targetStr)) {
            return "";
        }
        String stringNew = targetStr.length() > strlength ? targetStr.substring(0, strlength) : targetStr;

        return stringNew;

    }

    /**
     * double转String,保留小数点后两位
     *
     * @param num
     * @return
     */
    public static String doubleToString(double num) {
        //使用0.00不足位补0，#.##仅保留有效位
        return new DecimalFormat("0.00").format(num);
    }

    /**
     * 格式化文件大小
     */
    public static String fileSize(double number) {
        return String.valueOf(doubleToString(number / 1024 / 1024)) + "MB";
    }

    /**
     * 获取升级版本名称
     */
    public static String getFormatStr(String str) {
        StringBuilder builder = new StringBuilder();
        String[] data = str.split("");
        for (int i = 1; i < data.length; i++) {
            if (i != 1) {
                builder.append(".");
            }
            builder.append(data[i]);
        }
        return builder.toString();
    }

    /**
     * 字符串分割
     */
    public static List<String> getArrayString(String str, String regex) {
        List<String> mList = new ArrayList<>();
        if (str != null) {
            String[] strs = str.split(regex);
            for (int i = 0; i < strs.length; i++) {
                mList.add(strs[i]);
            }
        }
        return mList;
    }

    public static String getWebText(String str, String title) {
        StringBuilder builder = new StringBuilder();
        builder.append("<html>");
        builder.append("<title>");
        builder.append(title);
        builder.append("</title>");
        builder.append("<body>");
        builder.append(str);
        builder.append("</body>");
        builder.append("<html>");
        return builder.toString();
    }

    public static String getHtmlData(String bodyHtml) {
        String head = "<head>" +
                "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> " +
                "<style>img{max-width: 100%; width:auto; height:auto;}</style>" +
                "</head>";
        return "<html>" + head + "<body>" + bodyHtml + "</body></html>";
    }

    /**
     * 转换为万
     */
    public static String getUnitStringText(String str) {
        return getUnitText(Integer.parseInt(str));
    }

    public static String getUnitText(int num) {
        if (num > 10000) {
            double x = num / 10000.0;
            return doubleToString(x) + "万";
        } else {
            return String.valueOf(num);
        }
    }

    public static Spanned getValueText(String color, String key, String value) {
        StringBuilder string = new StringBuilder();
        string.append(key);
        string.append("<font color=\"" + color + "\">");
        string.append(value);
        string.append("</font>");
        return Html.fromHtml(string.toString());
    }

    public static Spanned getValueText(String color, String key, String value, String keys) {
        StringBuilder string = new StringBuilder();
        string.append(key);
        string.append("<font color=\"" + color + "\">");
        string.append(value);
        string.append("</font>");
        string.append(keys);
        return Html.fromHtml(string.toString());
    }

    public static Spanned getValueText(String color, String key, String value, String keys, String values) {
        StringBuilder string = new StringBuilder();
        string.append(key);
        string.append("<font color=\"" + color + "\">");
        string.append(value);
        string.append("</font>");
        string.append(keys);
        string.append("<font color=\"" + color + "\">");
        string.append(values);
        string.append("</font>");
        return Html.fromHtml(string.toString());
    }

    public static String getString(Context context, int resId) {
        return context.getString(resId);
    }

}
